#include "StdAfx.h"
#include "cParticle.h"
#include "d3dUtil.h"
#include "colorDef.h"

struct Particle
{
	D3DXVECTOR3 _position;
	D3DCOLOR    _color;
	static const DWORD FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE;;
};

cParticle::cParticle(void)
{
	_vb     = 0;
	_tex    = 0;
}

cParticle::~cParticle(void)
{
	SAFE_RELEASE(_vb);
	SAFE_RELEASE(_tex);
}

bool cParticle::init(char* texFileName)
{

	HRESULT hr = 0;

	hr = gd3dDevice->CreateVertexBuffer(
		_vbSize * sizeof(Particle),
		D3DUSAGE_DYNAMIC | D3DUSAGE_POINTS | D3DUSAGE_WRITEONLY,
		Particle::FVF,
		D3DPOOL_DEFAULT, // D3DPOOL_MANAGED can't be used with D3DUSAGE_DYNAMIC 
		&_vb,
		0);

	if(FAILED(hr))
	{
		::MessageBox(0, "CreateVertexBuffer() - FAILED", "PSystem", 0);
		return false;
	}

	hr = D3DXCreateTextureFromFile(
		gd3dDevice,
		texFileName,
		&_tex);

	if(FAILED(hr))
	{
		::MessageBox(0, "D3DXCreateTextureFromFile() - FAILED", "PSystem", 0);
		return false;
	}

	return true;
}

void cParticle::reset()
{
	std::list<Attribute>::iterator i;
	for(i = _particles.begin(); i != _particles.end(); i++)
	{
		resetParticle( &(*i) );
	}
}

void cParticle::addParticle()
{
	Attribute attribute;

	resetParticle(&attribute);

	_particles.push_back(attribute);
}

void cParticle::preRender()
{
	gd3dDevice->SetRenderState(D3DRS_LIGHTING, false);
	gd3dDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, true);
	gd3dDevice->SetRenderState(D3DRS_POINTSCALEENABLE, true); 
	gd3dDevice->SetRenderState(D3DRS_POINTSIZE, FtoDw(_size));
	gd3dDevice->SetRenderState(D3DRS_POINTSIZE_MIN, FtoDw(0.0f));

	// control the size of the particle relative to distance
	gd3dDevice->SetRenderState(D3DRS_POINTSCALE_A, FtoDw(0.0f));
	gd3dDevice->SetRenderState(D3DRS_POINTSCALE_B, FtoDw(0.0f));
	gd3dDevice->SetRenderState(D3DRS_POINTSCALE_C, FtoDw(1.0f));

	// use alpha from texture
	gd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
	gd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);

	gd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
	gd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
	gd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
}

void cParticle::postRender()
{
	gd3dDevice->SetRenderState(D3DRS_LIGHTING,          true);
	gd3dDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, false);
	gd3dDevice->SetRenderState(D3DRS_POINTSCALEENABLE,  false);
	gd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,  false);
}

void cParticle::render()
{
	if( !_particles.empty() )
	{
		//
		// set render states
		//

		preRender();

		D3DXMATRIX world;
		D3DXMatrixIdentity(&world);
		gd3dDevice->SetTransform(D3DTS_WORLD, &world);

		gd3dDevice->SetTexture(0, _tex);
		gd3dDevice->SetFVF(Particle::FVF);
		gd3dDevice->SetStreamSource(0, _vb, 0, sizeof(Particle));

		//
		// render batches one by one
		//

		// start at beginning if we're at the end of the vb
		if(_vbOffset >= _vbSize)
			_vbOffset = 0;

		Particle* v = 0;

		_vb->Lock(
			_vbOffset    * sizeof( Particle ),
			_vbBatchSize * sizeof( Particle ),
			(void**)&v,
			_vbOffset ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD);

		DWORD numParticlesInBatch = 0;

		//
		// Until all particles have been rendered.
		//
		std::list<Attribute>::iterator i;
		for(i = _particles.begin(); i != _particles.end(); i++)
		{
			if( i->_isAlive )
			{
				//
				// Copy a batch of the living particles to the
				// next vertex buffer segment
				//
				v->_position = i->_position;
				v->_color    = (D3DCOLOR)i->_color;
				v++; // next element;

				numParticlesInBatch++; //increase batch counter

				// if this batch full?
				if(numParticlesInBatch == _vbBatchSize) 
				{
					//
					// Draw the last batch of particles that was
					// copied to the vertex buffer. 
					//
					_vb->Unlock();

					gd3dDevice->DrawPrimitive(
						D3DPT_POINTLIST,
						_vbOffset,
						_vbBatchSize);

					//
					// While that batch is drawing, start filling the
					// next batch with particles.
					//

					// move the offset to the start of the next batch
					_vbOffset += _vbBatchSize; 

					// don't offset into memory thats outside the vb's range.
					// If we're at the end, start at the beginning.
					if(_vbOffset >= _vbSize) 
						_vbOffset = 0;       

					_vb->Lock(
						_vbOffset    * sizeof( Particle ),
						_vbBatchSize * sizeof( Particle ),
						(void**)&v,
						_vbOffset ? D3DLOCK_NOOVERWRITE : D3DLOCK_DISCARD);

					numParticlesInBatch = 0; // reset for new batch
				}	
			}
		}

		_vb->Unlock();

		// its possible that the LAST batch being filled never 
		// got rendered because the condition 
		// (numParticlesInBatch == _vbBatchSize) would not have
		// been satisfied.  We draw the last partially filled batch now.

		if( numParticlesInBatch )
		{
			gd3dDevice->DrawPrimitive(
				D3DPT_POINTLIST,
				_vbOffset,
				numParticlesInBatch);
		}

		// next block
		_vbOffset += _vbBatchSize; 

		//
		// reset render states
		//

		postRender();
	}
}

bool cParticle::isEmpty()
{
	return _particles.empty();
}

bool cParticle::isDead()
{
	std::list<Attribute>::iterator i;
	for(i = _particles.begin(); i != _particles.end(); i++)
	{
		// is there at least one living particle?  If yes,
		// the system is not dead.
		if( i->_isAlive )
			return false;
	}
	// no living particles found, the system must be dead.
	return true;
}

void cParticle::removeDeadParticles()
{
	std::list<Attribute>::iterator i;

	i = _particles.begin();

	while( i != _particles.end() )
	{
		if( i->_isAlive == false )
		{
			// erase returns the next iterator, so no need to
			// incrememnt to the next one ourselves.
			i = _particles.erase(i); 
		}
		else
		{
			i++; // next in list
		}
	}
}

DWORD cParticle::FtoDw( float f )
{
	return *((DWORD*)&f);
}
